/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.api.facade.impl;

import com.pingan.haofang.searchcloud.api.CollectionConfigManager;
import com.pingan.haofang.searchcloud.api.StorageCluster;
import com.pingan.haofang.searchcloud.api.constants.EngineType;
import com.pingan.haofang.searchcloud.api.facade.CollectionConfigFacade;
import com.pingan.haofang.searchcloud.api.schema.IndexSchema;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 索引配置实现
 *
 * @author zhangbi617
 * @date 2017-07-17
 */
@Service
public class CollectionConfigFacadeImpl implements CollectionConfigFacade, ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    private Map<EngineType, CollectionConfigManager> serviceMap = new HashMap<>();

    @Override
    public boolean create(StorageCluster storageCluster, IndexSchema schema, String configNameInStorage) {
        return serviceMap.get(storageCluster.getEngineType()).create(storageCluster.getClusterHost(),
                schema, configNameInStorage);
    }

    @Override
    public boolean delete(StorageCluster storageCluster, String configNameInStorage) {
        return serviceMap.get(storageCluster.getEngineType()).delete(storageCluster.getClusterHost(), configNameInStorage);
    }

    @Override
    @ManagedOperation
    public List<String> listAllConfigNames(StorageCluster storageCluster){
        return serviceMap.get(storageCluster.getEngineType())
                .getAllConfigNames(storageCluster.getClusterHost());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, CollectionConfigManager> map = applicationContext.getBeansOfType(CollectionConfigManager.class);
        for (CollectionConfigManager manager : map.values()) {
            this.serviceMap.put(manager.getEngineType(), manager);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
